package com.isoft.farm.service.Impl;

import com.isoft.farm.common.PageObject;
import com.isoft.farm.common.ServiceException;
import com.isoft.farm.dao.SysLogDao;
import com.isoft.farm.entity.SysLog;
import com.isoft.farm.service.SysLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysLogServiceImpl implements SysLogService {
   @Autowired
   SysLogDao sysLogDao;


    @Override
    public PageObject<SysLog> findPageObjects(String username, Integer pageCurrent) {
        if (pageCurrent<1||pageCurrent==null){
            throw new IllegalArgumentException("当前页码不正确");
        }
        int rows=sysLogDao.getRowCount(username);
        if (rows<=0){
//            throw new RuntimeException("系统没有查询到对应记录");
            throw new ServiceException("系统没有查询到对应记录");
        }
        int pageSize=3;
        int startIndex=(pageCurrent-1)*pageSize;

        List<SysLog> records=sysLogDao.findPageObjects(username,startIndex,pageSize);
//        PageObject<SysLog> pageObject=new PageObject<>();
//        pageObject.setRowCount(rows);
//        pageObject.setPageSize(pageSize);
//        pageObject.setPageCurrent(pageCurrent);
//        pageObject.setRecords(records);
//        int pageCount=rows/pageSize;
//        if(rows%pageSize!=0){
//            pageCount++;
//        }
//        pageObject.setPageCount(pageCount);
//        return pageObject;
        return new PageObject<SysLog>(pageCurrent,pageSize,rows,records);


    }

    @Override
    public int deleteObjects(Integer... ids) {
        if(ids==null||ids.length==0){
            throw new IllegalArgumentException("请选择一个");
        }
        int rows;
        try {
            rows=sysLogDao.deleteObjects(ids);
        }catch (Throwable e){
            e.printStackTrace();
            throw new ServiceException("系统故障，正在恢复中");
        }
        if(rows==0){
            throw new ServiceException("记录已经不存在了！");
        }
        return rows;
    }

    @Override
    public void saveObject(SysLog sysLog) {
        try{
            sysLogDao.insertObject(sysLog);
        }catch (Throwable e){
            e.printStackTrace();
            throw new  ServiceException("系统异常，正在修复中");
        }

    }
}
